<template>
  <div class="invoice-reimbursement-container">
    <div class="navbar">
      <el-row :gutter="20">
        <el-col :span="8">
          <h2 style="margin: 0;">发票报销系统</h2>
        </el-col>
      </el-row>
    </div>

    <div style="padding: 20px;">
      <!-- 上传区域单独一行 -->
      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="24">
          <!-- 文件上传区域 -->
          <el-card class="upload-card">
            <template #header>
              <el-icon><UploadFilled /></el-icon> 上传发票/附件
            </template>
            <el-upload
              ref="uploadRef"
              class="upload-demo"
              drag
              :file-list="fileList"
              :auto-upload="false"
              :on-change="handleFileChange"
              :on-remove="handleFileRemove"
              :accept="acceptTypes"
              multiple
            >
              <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
              <div class="el-upload__text">
                点击或拖拽文件到此处上传<br>
                <span class="el-upload__hint">支持 JPG、PNG、PDF 格式，单文件不超过10MB</span>
              </div>
            </el-upload>

            <div class="file-status-hint" style="margin-top: 15px;">
              <template v-if="validFileList.length > 0">
                <el-tag type="success" effect="light">
                  有效文件: {{ validFileList.length }}个
                </el-tag>
              </template>
              <template v-if="invalidFiles.length > 0">
                <el-tag type="danger" effect="light">
                  无效文件: {{ invalidFiles.length }}个
                </el-tag>
              </template>
            </div>

            <!-- 按钮区域：开始识别和清空所有并排显示 -->
            <div class="upload-actions" style="margin-top: 15px; display: flex; gap: 10px; justify-content: center;">
              <el-button 
                type="primary" 
                @click="startRecognition"
                :disabled="isRecognizing || validFileList.length === 0"
                style="min-width: 120px;"
              >
                <el-icon v-if="isRecognizing"><Loading /></el-icon>
                <span v-if="isRecognizing">识别中...</span>
                <span v-else>开始识别</span>
              </el-button>
              
              <el-button 
                type="warning" 
                style="border: 1px solid #ddd; min-width: 120px;"
                @click="clearAll"
                :disabled="isRecognizing || isSubmitting || fileList.length === 0"
              >
                <el-icon><RefreshLeft /></el-icon> 清空所有
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 识别结果和费用清单区域 -->
      <el-row :gutter="20">
        <el-col :span="24">
          <!-- 识别结果区域 -->
          <el-card class="result-card">
            <template #header>
              <el-icon><Document /></el-icon> 
              <span>识别结果 (共 {{ recognitionResults.length }} 项)</span>
            </template>

            <template v-if="recognitionResults.length === 0">
              <div class="empty-hint">
                暂无识别结果，请上传文件并点击"开始识别"
              </div>
            </template>

            <template v-else>
              <!-- 有效发票 - 始终显示，默认折叠 -->
              <template v-if="validInvoices.length > 0">
                <h3 style="margin-top: 20px; margin-bottom: 10px; display: flex; align-items: center;">
                  <el-icon color="#27ae60"><Check /></el-icon> 
                  <span style="margin-right: 8px;">有效发票</span>
                  <el-tag type="success" effect="light">
                    {{ validInvoices.length }} 项
                  </el-tag>
                </h3>
                <el-collapse v-model="activeValidInvoiceNames" @change="handleCollapseChange" :accordion="false">
                  <el-collapse-item 
                    v-for="invoice in validInvoices" 
                    :key="invoice._uid"
                    :title="`${invoice.file_name || invoice.fileName} (发票号: ${invoice.data?.invoice_no || '未识别'})`"
                    :name="invoice._uid"
                  >
                    <div class="invoice-content">
                      <el-descriptions :column="1" border>
                        <el-descriptions-item label="发票号码">{{ invoice.data?.invoice_no || '未识别' }}</el-descriptions-item>
                        <el-descriptions-item label="开票日期">{{ invoice.data?.date || '未识别' }}</el-descriptions-item>
                        <el-descriptions-item label="销售方">{{ invoice.data?.merchant || '未识别' }}</el-descriptions-item>
                        <el-descriptions-item label="购买方">{{ invoice.data?.buyer || '未识别' }}</el-descriptions-item>
                        <el-descriptions-item label="价税合计">{{ invoice.data?.total_amount || '未识别' }}</el-descriptions-item>
                        <el-descriptions-item label="发票类型">{{ invoice.data?.type_description || invoice.data?.type || '未识别' }}</el-descriptions-item>
                      </el-descriptions>

                      <h4 style="margin-top: 15px;">项目明细</h4>
                      <el-table 
                        :data="invoice.data?.items || []" 
                        border 
                        style="width: 100%;"
                        size="small"
                        :table-layout="'auto'"
                      >
                        <el-table-column prop="Name" label="项目名称" min-width="200" :show-overflow-tooltip="true"></el-table-column>
                        <el-table-column prop="Specification" label="规格型号" min-width="150"></el-table-column>
                        <el-table-column prop="Unit" label="单位" min-width="80"></el-table-column>
                        <el-table-column prop="Quantity" label="数量" min-width="100"></el-table-column>
                        <el-table-column prop="Price" label="单价" min-width="120"></el-table-column>
                        <el-table-column prop="Total" label="金额" min-width="120"></el-table-column>
                        <el-table-column prop="Tax" label="税额" min-width="120"></el-table-column>
                        <el-table-column label="操作" min-width="80">
                          <template #default="scope">
                            <el-button 
                              type="text" 
                              size="small" 
                              @click="addToReimbursement(scope.row, invoice)"
                              :disabled="isItemAdded(scope.row, invoice.data?.invoice_no) || isSubmitting || invoice.is_duplicate"
                            >
                              <el-icon><Plus /></el-icon> 添加
                            </el-button>
                          </template>
                        </el-table-column>
                      </el-table>

                      <div style="text-align: right; margin-top: 10px;">
                        <el-button 
                          type="primary" 
                          size="small"
                          @click="addAllToReimbursement(invoice.data?.items || [], invoice)"
                          :disabled="areAllItemsAdded(invoice.data?.items || [], invoice.data?.invoice_no) || isSubmitting || invoice.is_duplicate"
                        >
                          <el-icon><List /></el-icon> 添加全部
                        </el-button>
                      </div>
                    </div>
                  </el-collapse-item>
                </el-collapse>
              </template>

              <!-- 无效发票 - 始终显示，默认折叠 -->
              <template v-if="invalidInvoices.length > 0">
                <h3 style="margin-top: 20px; margin-bottom: 10px; display: flex; align-items: center;">
                  <el-icon color="#e74c3c"><WarningFilled /></el-icon> 
                  <span style="margin-right: 8px;">无效发票</span>
                  <el-tag type="danger" effect="light">
                    {{ invalidInvoices.length }} 项
                  </el-tag>
                </h3>
                <el-collapse v-model="activeInvalidInvoiceNames" @change="handleCollapseChange" :accordion="false">
                    <el-collapse-item 
                      v-for="invoice in invalidInvoices" 
                      :key="invoice._uid"
                      :title="`${invoice.file_name || invoice.fileName} (发票号: ${invoice.data?.invoice_no || '未识别'}) - ${invoice.data?.type_description || '无效发票'}`"
                      :name="invoice._uid"
                    >
                    <div class="invoice-content">
                      <el-descriptions :column="1" border>
                        <el-descriptions-item label="发票号码">
                          <template v-if="invoice.is_duplicate && !invoice.data?.invoice_no">
                            <span style="color: #e74c3c;">未识别发票号，系统判定为重复</span>
                          </template>
                          <template v-else>
                            {{ invoice.data?.invoice_no || '未识别' }}
                          </template>
                        </el-descriptions-item>
                        <el-descriptions-item label="状态">
                          <el-tag type="danger" v-if="invoice.is_duplicate" style="background-color: #f5222d;">重复发票</el-tag>
                          <el-tag type="warning" v-else>
                            {{ invoice.data?.type_description || '无效发票' }}
                          </el-tag>
                        </el-descriptions-item>
                        <el-descriptions-item label="开票日期">{{ invoice.data?.date || '未识别' }}</el-descriptions-item>
                        <el-descriptions-item label="销售方">{{ invoice.data?.merchant || '未识别' }}</el-descriptions-item>
                        <el-descriptions-item label="购买方">{{ invoice.data?.buyer || '未识别' }}</el-descriptions-item>
                        <el-descriptions-item label="价税合计">{{ invoice.data?.total_amount || '未识别' }}</el-descriptions-item>
                      </el-descriptions>
                    </div>
                  </el-collapse-item>
                </el-collapse>
              </template>

              <!-- 普通附件 - 始终显示，默认折叠 -->
              <template v-if="normalAttachments.length > 0">
                <h3 style="margin-top: 20px; margin-bottom: 10px; display: flex; align-items: center;">
                  <el-icon color="#3498db"><Document /></el-icon> 
                  <span style="margin-right: 8px;">普通附件</span>
                  <el-tag type="info" effect="light">
                    {{ normalAttachments.length }} 项
                  </el-tag>
                </h3>
                <el-collapse v-model="activeAttachmentNames" @change="handleCollapseChange" :accordion="false">
                  <el-collapse-item 
                    v-for="attachment in normalAttachments" 
                    :key="attachment._uid"
                    :title="attachment.file_name || attachment.fileName"
                    :name="attachment._uid"
                  >
                    <div class="invoice-content">
                      <el-descriptions :column="1" border>
                        <el-descriptions-item label="文件名称">{{ attachment.file_name || attachment.fileName }}</el-descriptions-item>
                        <el-descriptions-item label="状态">
                          <el-tag type="info">
                            {{ attachment.success ? '识别成功（非发票）' : '无法识别' }}
                          </el-tag>
                        </el-descriptions-item>
                      </el-descriptions>

                      <div style="text-align: right; margin-top: 10px;">
                        <el-button 
                          type="primary" 
                          size="small"
                          @click="openManualMarkDialog(attachment)"
                          :disabled="isSubmitting"
                        >
                          <el-icon><Edit /></el-icon> 手动标记为发票
                        </el-button>
                      </div>
                    </div>
                  </el-collapse-item>
                </el-collapse>
              </template>

              <template v-if="
                validInvoices.length === 0 &&
                invalidInvoices.length === 0 &&
                normalAttachments.length === 0
              ">
                <div class="empty-hint">
                  没有识别到任何内容
                </div>
              </template>
            </template>
          </el-card>

          <!-- 费用清单区域 -->
          <el-card class="reimbursement-card" style="margin-top: 40px;">
            <template #header>
              <el-icon><List /></el-icon> 
              <span style="margin-left: 8px;">费用清单</span>
              <el-badge :value="reimbursementList.length" class="item" v-if="reimbursementList.length > 0">
              </el-badge>
            </template>

            <template v-if="reimbursementList.length > 0">
              <el-row :gutter="20" style="margin-top: 15px;">
                <el-col :span="12">
                  <el-form-item label="费用类别" required>
                    <el-select 
                      v-model="selectedCategory" 
                      placeholder="请选择费用类别"
                      style="width: 100%;"
                      :disabled="isSubmitting"
                    >
                      <el-option 
                        v-for="category in Object.keys(categoryMap)" 
                        :key="category"
                        :label="category"
                        :value="category"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              
              <!-- 报销事由单独一行，并限制200字 -->
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="用途/摘要" required>
                    <el-input 
                      v-model="reimbursementReason" 
                      placeholder="请填写用途、摘要" 
                      type="textarea" 
                      :rows="1"
                      style="width: 100%;"
                      :disabled="isSubmitting"
                      :maxlength="200"
                      show-word-limit
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            
              <el-table 
                v-if="renderReimbursementTable"
                :data="reimbursementList" 
                border 
                style="width: 100%; padding: 16px;"
                :header-cell-style="{ verticalAlign: 'middle' }"
                :cell-style="{ padding: '12px 10px', verticalAlign: 'middle' }"
                :key="reimbursementListKey"
                :table-layout="'auto'"
              >
                <el-table-column prop="source_invoice_no" label="发票号码" min-width="200"></el-table-column>
                <el-table-column prop="Name" label="项目名称" min-width="250" :show-overflow-tooltip="true"></el-table-column>
                <el-table-column prop="Specification" label="规格型号" min-width="150"></el-table-column>
                <el-table-column prop="Unit" label="单位" min-width="80"></el-table-column>
                <el-table-column prop="Quantity" label="数量" min-width="100">
                  <template #default="scope">
                    <span>{{ scope.row.Quantity }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="Price" label="单价" min-width="120">
                  <template #default="scope">
                    <span>{{ formatNumber(scope.row.Price) }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="Total" label="金额" min-width="120">
                  <template #default="scope">
                    <span>{{ formatNumber(scope.row.Quantity * scope.row.Price) }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="Tax" label="税额" min-width="120">
                  <template #default="scope">
                    <span>{{ formatNumber(scope.row.Tax) }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="价税合计" min-width="120">
                  <template #default="scope">
                    <span>{{ formatNumber((parseFloat(scope.row.Total) || 0) + (parseFloat(scope.row.Tax) || 0)) }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" min-width="80">
                  <template #default="scope">
                    <el-button 
                      type="text" 
                      size="small" 
                      @click="removeFromReimbursement(scope.$index)"
                      :disabled="isSubmitting"
                    >
                      <ElIcon><CloseCircle /></ElIcon> 移除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              
              <div style="margin-top: 20px;">
                <el-descriptions :column="3" border>
                  <el-descriptions-item label="合计金额">
                    <span style="font-weight: bold;">¥{{ calculateTotal('Total') }}</span>
                  </el-descriptions-item>
                  <el-descriptions-item label="合计税额">
                    <span style="font-weight: bold;">¥{{ calculateTotal('Tax') }}</span>
                  </el-descriptions-item>
                  <el-descriptions-item label="价税合计" style="text-align: center;">
                    <span style="font-weight: bold; color: #27ae60;">¥{{ calculateTotalAmountWithTax() }}</span>
                  </el-descriptions-item>
                </el-descriptions>
                
                <el-descriptions :column="1" border style="margin-top: 10px;">
                  <el-descriptions-item label="价税合计（大写）">
                    <span style="font-weight: bold; font-size: 14px;">{{ convertToChinese(calculateTotalAmountWithTax()) }}</span>
                  </el-descriptions-item>
                </el-descriptions>
                
                <el-button 
                  type="primary" 
                  @click="submitReimbursement"
                  style="margin-top: 15px;"
                  :disabled="!selectedCategory || !reimbursementReason || isSubmitting || validInvoices.length === 0"
                >
                  <el-icon v-if="isSubmitting"><Loading /></el-icon>
                  <span v-if="isSubmitting">提交中...</span>
                  <span v-else>提交报销审批</span>
                </el-button>
              </div>
            </template>
            
            <!-- 费用清单无明细时的显示 -->
            <div v-else class="empty-hint reimbursement-empty">
              <div class="empty-icon">
                <el-icon><List /></el-icon>
              </div>
              <div class="empty-text">费用清单为空</div>
              <div class="empty-description">请从上方识别结果中添加项目到费用清单</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      
      <!-- 手动输入发票号弹窗 -->
      <el-dialog v-model="manualMarkVisible" title="手动输入发票号（转为发票）" width="500px">
        <el-form ref="markForm" :model="markForm" :rules="markRules" label-width="120px">
          <el-form-item label="附件名称" disabled>
            <el-input v-model="markForm.fileName"></el-input>
          </el-form-item>
          <el-form-item label="发票号码" prop="invoiceNo">
            <el-input 
              v-model="markForm.invoiceNo" 
              placeholder="请输入发票号"
            ></el-input>
          </el-form-item>
          <el-form-item label="开票日期" prop="date">
            <el-date-picker 
              v-model="markForm.date" 
              type="date" 
              placeholder="请选择开票日期"
              style="width: 100%;"
            ></el-date-picker>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="manualMarkVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmManualMark">确认转为发票</el-button>
        </template>
      </el-dialog>

      <!-- 识别状态弹窗 -->
      <el-dialog
        v-model="recognitionDialogVisible"
        title="发票识别中"
        width="600px"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :show-close="false"
        center
      >
        <div class="recognition-status-container">
          <!-- 整体进度 -->
          <div class="overall-progress" style="margin-bottom: 20px;">
            <div style="display: flex; justify-content: space-between; margin-bottom: 8px;">
              <span>整体进度</span>
              <span>{{ recognitionProgress }}%</span>
            </div>
            <el-progress
              :percentage="recognitionProgress"
              :stroke-width="8"
              :status="recognitionProgress === 100 ? 'success' : ''"
            ></el-progress>
          </div>

          <!-- 单个文件进度列表 -->
          <div class="file-progress-list" style="max-height: 300px; overflow-y: auto;">
            <template v-if="fileRecognitionStatus.length > 0">
              <div 
                class="file-progress-item" 
                style="display: flex; justify-content: space-between; align-items: center; padding: 8px 0; border-bottom: 1px solid #f0f0f0;"
                v-for="(file, index) in fileRecognitionStatus"
                :key="index"
              >
                <div style="flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; margin-right: 16px;">
                  <el-icon :color="file.status === 'success' ? '#67c23a' : file.status === 'error' ? '#f56c6c' : '#909399'">
                    <Check v-if="file.status === 'success'" />
                    <Close v-if="file.status === 'error'" />
                    <Loading v-if="file.status === 'loading'" />
                  </el-icon>
                  <span style="margin-left: 8px;">{{ file.name }}</span>
                </div>
                <div style="display: flex; align-items: center;">
                  <span style="margin-right: 16px; color: #666;">
                    {{ file.status === 'loading' ? '识别中' : file.status === 'success' ? '识别成功' : '识别失败' }}
                  </span>
                  <span v-if="file.time" style="color: #999; font-size: 12px;">{{ file.time }}s</span>
                </div>
              </div>
            </template>
            <template v-else>
              <div class="empty-hint" style="padding: 20px 0;">
                准备开始识别...
              </div>
            </template>
          </div>
        </div>

        <!-- 弹窗底部按钮 -->
        <template #footer>
          <el-button
            type="primary"
            :disabled="isRecognizing"
            @click="recognitionDialogVisible = false"
          >
            {{ isRecognizing ? '识别中...' : '关闭' }}
          </el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { 
  UploadFilled, Plus, Loading, Document, List, WarningFilled,
  Edit, CloseCircle, Check, RefreshLeft, Close
} from '@element-plus/icons-vue';
import axios from 'axios';  // 导入axios
import { ElMessage } from 'element-plus';

// 预置报销类型模板
const categoryMap = {
  '员工福利': 'option-1758272532231',
  '网络运营': 'option-1758272613527',
  '日常费用': 'option-1758272622422',
  '快递费': 'option-1758272630077',
  '运输费': 'option-1758272652293',
  '办公费': 'option-1758272656591',
  '中介服务': 'option-1758272667373',
  '员工团建': 'option-1758272681645',
  '资产采购': 'option-1758272700275'
};

// 修复ResizeObserver错误
onMounted(() => {
  // 忽略ResizeObserver的特定错误
  const originalErrorHandler = window.onerror;
  window.onerror = function(message, source, lineno, colno, error) {
    if (message.includes('ResizeObserver loop completed with undelivered notifications')) {
      return true; // 阻止错误传播
    }
    if (originalErrorHandler) {
      return originalErrorHandler(message, source, lineno, colno, error);
    }
    return false;
  };
  
  // 处理未捕获的Promise错误
  window.addEventListener('unhandledrejection', (event) => {
    if (event.reason && event.reason.message && 
        event.reason.message.includes('ResizeObserver loop completed with undelivered notifications')) {
      event.preventDefault();
    }
  });
});

// 定义支持的文件类型
const acceptTypes = ref('.jpg,.jpeg,.png,.pdf');

// 生成唯一ID
const generateUid = () => {
  const uid = Date.now().toString(36) + Math.random().toString(36).substr(2, 5);
  return uid;
};

// 生成审批ID (新增)
const generateApprovalId = () => {
  return `APR${Date.now().toString(36)}${Math.random().toString(36).substr(2, 8)}`;
};

// 工具函数：生成带时间戳的日志前缀
const getLogPrefix = (funcName) => `[${new Date().toLocaleString()}] [${funcName}]`;

// 上传组件ref和文件状态管理
const uploadRef = ref(null);
const validFileList = ref([]); // 存储有效文件
const invalidFiles = ref([]); // 存储无效文件及错误信息
const loading = ref(false);

// 状态管理 - 默认空数组确保折叠面板默认折叠
const activeValidInvoiceNames = ref([]);
const activeInvalidInvoiceNames = ref([]);
const activeAttachmentNames = ref([]);
const reimbursementList = ref([]);
const reimbursementListKey = ref(generateUid());

// 基础状态
const fileList = ref([]);
const isRecognizing = ref(false);
const recognitionResults = ref([]);
const selectedCategory = ref('');
const reimbursementReason = ref('');
const isSubmitting = ref(false);
const pendingApprovalId = ref('');
const renderReimbursementTable = ref(true);

// 识别状态弹窗相关
const recognitionDialogVisible = ref(false); // 弹窗显示状态
const recognitionProgress = ref(0); // 整体识别进度（0-100）
const fileRecognitionStatus = ref([]); // 单个文件识别状态列表
const totalFilesToRecognize = ref(0); // 待识别文件总数

// 手动输入发票号弹窗
const manualMarkVisible = ref(false);
const currentMarkItem = ref(null);
const markForm = {
  fileName: '',
  invoiceNo: '',
  date: ''
};
const markRules = {
  invoiceNo: [
    { required: true, message: '请输入发票号码', trigger: 'blur' }
  ]
};

// 计算属性：基于后端返回的type_description判断发票状态
const validInvoices = computed(() => {
  return recognitionResults.value.filter(item => {
    // 有效发票判断：是发票 + 识别成功 + type_description为"有效发票" + 非重复
    return item.is_invoice === true 
      && item.success === true
      && item.data?.type_description === '有效发票'
      && !item.is_duplicate;
  });
});

const invalidInvoices = computed(() => {
  // 无效发票判断：是发票 + 识别成功 + 不是有效发票
  return recognitionResults.value.filter(item => 
    item.is_invoice === true 
    && item.success === true
    && (item.data?.type_description !== '有效发票' || item.is_duplicate)
  );
});

const normalAttachments = computed(() => {
  // 普通附件：不是发票的附件
  return recognitionResults.value.filter(item => item.is_invoice === false);
});

const submitAttachments = () => {
  // 收集所有要提交的附件信息
  return recognitionResults.value.map(item => ({
    name: item.file_name || item.fileName,
    type: item.is_invoice ? '发票' : '普通附件',
    file_key: item.file_key
  }));
};

// 判断是否所有项目已添加
const areAllItemsAdded = (items, invoiceNo) => {
  if (!items || items.length === 0) return false;
  return items.every(item => isItemAdded(item, invoiceNo));
};

// 文件上传变化处理 - 仅做基础验证，详细验证交给后端
const handleFileChange = (file, newFileList) => {
  const prefix = getLogPrefix('handleFileChange');
  console.debug(`${prefix} 文件列表变化，新文件总数=${newFileList.length}`);
  
  // 重置文件状态
  const validFiles = [];
  const invalidFilesTemp = [];

  // 仅做基础的前端验证，详细验证交给后端
  newFileList.forEach(fileItem => {
    console.debug(`${prefix} 校验文件: name=${fileItem.name}, type=${fileItem.raw?.type}, size=${fileItem.size}byte`);
    
    // 检查文件类型
    const isImage = fileItem.raw.type === 'image/jpeg' || fileItem.raw.type === 'image/png';
    const isPdf = fileItem.raw.type === 'application/pdf';
    const isAcceptable = isImage || isPdf;

    // 检查文件大小（10MB）
    const maxSize = 10 * 1024 * 1024;
    const isSizeValid = fileItem.size <= maxSize;

    // 标记文件状态
    if (isAcceptable && isSizeValid) {
      validFiles.push(fileItem);
      console.debug(`${prefix} 文件有效: ${fileItem.name}`);
    } else {
      // 收集错误信息
      let errorMsg = '';
      if (!isAcceptable) {
        errorMsg = `文件"${fileItem.name}"类型不支持`;
      } else if (!isSizeValid) {
        errorMsg = `文件"${fileItem.name}"超过10MB`;
      }
      invalidFilesTemp.push({ ...fileItem, errorMsg });
      console.warn(`${prefix} 文件无效: ${errorMsg}`);
    }

    // 错误提示
    if (!isAcceptable || !isSizeValid) {
      console.warn(`文件"${fileItem.name}"无效: ${!isAcceptable ? '仅支持JPG、PNG、PDF格式' : '大小超过10MB'}`);
    }
  });

  // 响应式更新文件列表
  validFileList.value = validFiles;
  invalidFiles.value = invalidFilesTemp;
  fileList.value = [...newFileList]; // 深拷贝确保响应式更新
  console.debug(`${prefix} 文件校验完成: 有效=${validFiles.length}个, 无效=${invalidFilesTemp.length}个`);
};

// 处理文件删除
const handleFileRemove = (file, newFileList) => {
  const prefix = getLogPrefix('handleFileRemove');
  console.debug(`${prefix} 文件被删除: ${file.name}, 剩余文件数=${newFileList.length}`);
  // 调用已有的文件处理逻辑重新计算有效/无效文件
  handleFileChange(file, newFileList);
};

// 清除历史数据
const clearAllHistory = () => {
  const prefix = getLogPrefix('clearAllHistory');
  console.debug(`${prefix} 开始清除历史数据`);
  
  recognitionResults.value = [];
  reimbursementList.value = [];
  selectedCategory.value = '';
  reimbursementReason.value = '';
  reimbursementListKey.value = generateUid();
  
  // 重置文件状态
  validFileList.value = [];
  invalidFiles.value = [];
  
  console.debug(`${prefix} 历史数据清除完成`);
};

// 清空所有内容（文件+历史）
const clearAll = () => {
  const prefix = getLogPrefix('clearAll');
  console.debug(`${prefix} 触发清空所有内容`);
  
  clearAllHistory();
  
  // 清空上传组件的文件列表
  if (uploadRef.value) {
    uploadRef.value.clearFiles();
    console.debug(`${prefix} 上传组件文件列表已清空`);
  } else {
    console.warn(`${prefix} 上传组件ref未获取到，无法清空组件内文件`);
  }
  
  fileList.value = [];
  validFileList.value = [];
  invalidFiles.value = [];
};

// 防抖函数
const debounce = (fn, delay = 100) => {
  let timer = null;
  return function(...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
      timer = null;
    }, delay);
  };
};

// 处理折叠面板变化，解决ResizeObserver问题
const handleCollapseChange = debounce(() => {
  // 使用防抖和延迟处理ResizeObserver错误
  setTimeout(() => {
    requestAnimationFrame(() => {});
  }, 100); // 增加延迟时间以避免错误
});

// 自动添加有效发票明细到费用清单
const autoAddValidItems = (validInvoices) => {
  const prefix = getLogPrefix('autoAddValidItems');
  console.debug(`${prefix} 开始自动添加有效发票明细，共${validInvoices.length}张发票`);
  
  if (validInvoices.length === 0) return;
  
  renderReimbursementTable.value = false;
  
  setTimeout(() => {
    validInvoices.forEach(invoice => {
      const invoiceNo = invoice.data?.invoice_no;
      const items = invoice.data?.items || [];
      
      items.forEach((item, index) => {
        if (!isItemAdded({ ...item, index }, invoiceNo)) {
          reimbursementList.value.push({
            ...item,
            index,
            source_invoice_no: invoiceNo,
            source: invoice.file_name || invoice.fileName,
            originalPrice: parseFloat(item.Price) || 0,
            originalQuantity: parseFloat(item.Quantity) || 0,
            originalTotal: parseFloat(item.Total) || 0,
            originalTax: parseFloat(item.Tax) || 0,
            _uid: generateUid(),
            date: invoice.data?.date || ''
          });
        }
      });
    });
    
    reimbursementListKey.value = generateUid();
    renderReimbursementTable.value = true;
    console.debug(`${prefix} 自动添加完成，费用清单共${reimbursementList.value.length}项`);
  }, 0);
};

// 处理识别结果，改进重复发票判断逻辑
const handleRecognitionResult = (data) => {
  const prefix = getLogPrefix('handleRecognitionResult');
  console.debug(`${prefix} 开始处理识别结果，数据长度=${data?.length || 0}`);
  
  if (!data || !Array.isArray(data)) {
    console.error(`${prefix} 识别结果格式不正确，不是数组`);
    console.warn('识别结果格式错误');
    return;
  }
  
  // 1. 先处理所有项目，添加基础信息
  const tempResults = data.map(item => ({
    ...item,
    ...(item.standard_result || {}),
    fileName: item.file_name || (item.standard_result?.file_name || ''),
    _uid: generateUid(),
    is_duplicate: false, // 默认为非重复
  }));
  
  // 2. 检查并标记当前批次内的重复发票（根据发票号）
  const invoiceNoMap = new Map();
  
  tempResults.forEach(item => {
    // 只处理发票类型且成功识别了发票号
    if (item.is_invoice && item.success && item.data?.invoice_no) {
      const invoiceNo = item.data.invoice_no.trim(); // 去除首尾空格，避免因空格导致的误判
      
      // 检查是否为重复发票（当前批次内）
      if (invoiceNoMap.has(invoiceNo)) {
        // 后续出现的标记为重复
        item.is_duplicate = true;
      } else {
        // 第一次出现的不标记为重复
        invoiceNoMap.set(invoiceNo, item._uid);
        item.is_duplicate = false;
      }
      
      // 更新类型描述（如果是重复发票）
      if (item.is_duplicate) {
        item.data.type_description = `重复发票（${item.data?.type_description || ''}）`;
      }
    } else if (item.is_invoice && item.success) {
      // 对于未识别出发票号的发票，不标记为重复
      item.is_duplicate = false;
      if (!item.data?.type_description) {
        item.data.type_description = '未识别发票号';
      }
    }
  });
  
  // 3. 更新识别结果
  recognitionResults.value = tempResults;
  console.debug(`${prefix} 识别结果处理完成，有效发票数=${validInvoices.value.length}，无效发票数=${invalidInvoices.value.length}`);
  
  // 4. 自动添加有效发票明细到费用清单
  autoAddValidItems(validInvoices.value);
  
  // 5. 确保所有识别结果默认折叠（不设置active）
  activeValidInvoiceNames.value = [];
  activeInvalidInvoiceNames.value = [];
  activeAttachmentNames.value = [];
};

// 修改startRecognition函数中的错误处理部分
const startRecognition = async () => {
  const prefix = getLogPrefix('startRecognition'); // 添加日志前缀
  try {
    console.log(`${prefix} 开始发票识别，有效文件数=${validFileList.value.length}`);
    
    if (validFileList.value.length === 0) {
      console.warn('请先选择有效的文件');
      ElMessage.warning('请先选择有效的文件');
      return;
    }

    // 初始化识别状态弹窗
    totalFilesToRecognize.value = validFileList.value.length;
    recognitionProgress.value = 0;
    fileRecognitionStatus.value = validFileList.value.map(file => ({
      name: file.name,
      status: 'loading', // 初始状态：loading
      time: null
    }));
    recognitionDialogVisible.value = true; // 打开弹窗

    // 模拟进度更新（实际项目中可根据后端进度接口调整）
    const progressInterval = setInterval(() => {
      if (recognitionProgress.value < 90 && isRecognizing.value) {
        recognitionProgress.value += 5;
      }
    }, 1000);

    loading.value = true;
    isRecognizing.value = true; // 添加识别中状态标记
    
    // 清空之前的费用清单
    reimbursementList.value = [];
    
    // 构建FormData
    const formData = new FormData();
    validFileList.value.forEach(file => {
      console.log(`${prefix} 加入识别队列: fileName=${file.name}, size=${file.size}byte, type=${file.raw?.type}`);
      formData.append('image', file.raw, file.name);
    });
    
    console.log(`${prefix} 识别请求FormData构建完成，文件数=${validFileList.value.length}`);
    console.log(`${prefix} 开始调用API: /api/ocr/invoice`);
    
    // 调用API
    const startTime = Date.now();
    const response = await axios.post('/api/ocr/invoice', formData);
    
    const totalTime = ((Date.now() - startTime) / 1000).toFixed(2);
    console.log(`${prefix} API响应状态: ${response.status}，总耗时: ${totalTime}s`);

    // 清除进度更新定时器
    clearInterval(progressInterval);
    // 更新弹窗进度（全部成功）
    recognitionProgress.value = 100;
    fileRecognitionStatus.value = fileRecognitionStatus.value.map(item => ({
      ...item,
      status: 'success',
      time: totalTime
    }));

    if (response.data && response.data.code === 200) { // 后端用code=200表示成功
      ElMessage.success('发票识别成功');
      handleRecognitionResult(response.data.data); // 从results提取数据
      // 延迟关闭弹窗（让用户看到成功状态）
      setTimeout(() => {
        recognitionDialogVisible.value = false;
      }, 1000);
    } else {
      const errorMsg = response.data?.msg || '后端未返回错误信息'; // 后端错误信息在msg字段
      console.error(`${prefix} 识别失败 - 业务错误:`, {
        code: response.data?.code,
        message: errorMsg,
        responseData: response.data
      });
      ElMessage.error(`识别失败: ${errorMsg}`);
      // 更新弹窗为失败状态
      fileRecognitionStatus.value = fileRecognitionStatus.value.map(item => ({
        ...item,
        status: 'error',
        time: totalTime
      }));
    }
  } catch (error) {
    const totalTime = ((Date.now() - new Date()) / 1000).toFixed(2);
    // 更新弹窗为失败状态
    recognitionProgress.value = 100;
    fileRecognitionStatus.value = fileRecognitionStatus.value.map(item => ({
      ...item,
      status: 'error',
      time: totalTime
    }));

    console.error(`${prefix} 识别失败 - 异常错误:`, {
      message: error.message,
      stack: error.stack,
      responseStatus: error.response?.status,
      responseData: error.response?.data,
      requestUrl: error.config?.url,
      requestMethod: error.config?.method,
      timestamp: new Date().toISOString()
    });

    // 用户友好提示
    let errorInfo = [];
    if (error.response) {
      errorInfo.push(`状态码: ${error.response.status}`);
      if (error.response.data?.message) {
        errorInfo.push(`原因: ${error.response.data.message}`);
      }
    } else {
      errorInfo.push(error.message || '网络请求异常');
    }
    const errorMsg = `识别失败: ${errorInfo.join('，')}`;
    ElMessage.error(errorMsg);
  } finally {
    loading.value = false;
    isRecognizing.value = false; // 重置识别状态
    console.log(`${prefix} 识别流程结束`);
  }
};

// 检查项目是否已添加到费用清单
const isItemAdded = (item, invoiceNo) => {
  if (!item || !invoiceNo) return false;

  const key = `${invoiceNo}_${item.Name || item.Specification || ''}_${item.index || ''}`;
  return reimbursementList.value.some(i => {
    const iKey = `${i.source_invoice_no}_${i.Name || i.Specification || ''}_${i.index || ''}`;
    return iKey === key;
  });
};

// 添加项目到费用清单
const addToReimbursement = debounce((item, invoice) => {
  const prefix = getLogPrefix('addToReimbursement');
  const invoiceNo = invoice.data?.invoice_no;
  
  // 检查是否为重复发票
  if (invoice.is_duplicate) {
    console.warn(`${prefix} 无法添加重复发票项目: invoiceNo=${invoiceNo}, 项目名=${item.Name}`);
    ElMessage.warning('重复发票不允许添加到费用清单');
    return;
  }
  
  if (isItemAdded(item, invoiceNo)) {
    console.warn(`${prefix} 项目已存在，跳过添加: invoiceNo=${invoiceNo}, 项目名=${item.Name}`);
    return;
  }
  
  // 确保item有必要的属性且为数字类型
  const newItem = {
    ...item,
    source_invoice_no: invoiceNo,
    source: invoice.file_name || invoice.fileName,
    originalPrice: parseFloat(item.Price) || 0,
    originalQuantity: parseFloat(item.Quantity) || 0,
    originalTotal: parseFloat(item.Total) || 0,
    originalTax: parseFloat(item.Tax) || 0,
    _uid: generateUid(),
    date: invoice.data?.date || ''
  };
  
  // 修复表格渲染问题
  renderReimbursementTable.value = false;
  setTimeout(() => {
    reimbursementList.value.push(newItem);
    reimbursementListKey.value = generateUid();
    renderReimbursementTable.value = true;
  }, 0);
  
  console.debug(`${prefix} 项目添加成功: invoiceNo=${invoiceNo}, 项目名=${item.Name}, 费用清单总数=${reimbursementList.value.length}`);
}, 100);

// 添加所有项目到费用清单
const addAllToReimbursement = debounce((items, invoice) => {
  // 检查是否为重复发票
  if (invoice.is_duplicate) {
    ElMessage.warning('重复发票不允许添加到费用清单');
    return;
  }
  
  if (!items || items.length === 0) return;

  const invoiceNo = invoice.data?.invoice_no;
  renderReimbursementTable.value = false;
  setTimeout(() => {
    items.forEach((item, index) => {
      if (!isItemAdded({ ...item, index }, invoiceNo)) {
        reimbursementList.value.push({
          ...item,
          index, // 添加 index 作为唯一键
          source_invoice_no: invoiceNo,
          source: invoice.file_name || invoice.fileName,
          originalPrice: parseFloat(item.Price) || 0,
          originalQuantity: parseFloat(item.Quantity) || 0,
          originalTotal: parseFloat(item.Total) || 0,
          originalTax: parseFloat(item.Tax) || 0,
          _uid: generateUid(),
          date: invoice.data?.date || ''
        });
      }
    });
    reimbursementListKey.value = generateUid();
    renderReimbursementTable.value = true;
  }, 0);
}, 100);

// 从费用清单移除项目
const removeFromReimbursement = debounce((index) => {
  const prefix = getLogPrefix('removeFromReimbursement');
  if (index < 0 || index >= reimbursementList.value.length) {
    console.error(`${prefix} 索引无效: index=${index}, 清单长度=${reimbursementList.value.length}`);
    return;
  }
  
  // 延迟更新表格，避免ResizeObserver错误
  renderReimbursementTable.value = false;
  setTimeout(() => {
    const removedItem = reimbursementList.value[index];
    reimbursementList.value.splice(index, 1);
    reimbursementListKey.value = generateUid();
    renderReimbursementTable.value = true;
    
    console.debug(`${prefix} 项目移除成功: invoiceNo=${removedItem.source_invoice_no}, 项目名=${removedItem.Name}, 剩余总数=${reimbursementList.value.length}`);
  }, 0);
}, 100);

// 计算总计
const calculateTotal = (field) => {
  const prefix = getLogPrefix('calculateTotal');
  if (!field) {
    console.error(`${prefix} 未指定计算字段`);
    return '0.00';
  }
  
  let total = 0;
  reimbursementList.value.forEach(item => {
    const value = parseFloat(item[field] || 0);
    total += value;
  });
  
  return total.toFixed(2);
};

// 计算价税合计
const calculateTotalAmountWithTax = () => {
  const totalAmount = parseFloat(calculateTotal('Total')) || 0;
  const totalTax = parseFloat(calculateTotal('Tax')) || 0;
  return (totalAmount + totalTax).toFixed(2);
};

// 数字格式化
const formatNumber = (num) => {
  if (!num && num !== 0) return '0.00';
  return parseFloat(num).toFixed(2);
};

// 打开手动标记弹窗
const openManualMarkDialog = (attachment) => {
  currentMarkItem.value = attachment;
  markForm.fileName = attachment.file_name || attachment.fileName;
  markForm.invoiceNo = '';
  markForm.date = '';
  manualMarkVisible.value = true;
};

// 确认手动标记
const confirmManualMark = () => {
  // 这里可以添加表单验证逻辑
  if (!markForm.invoiceNo) {
    ElMessage.warning('请输入发票号码');
    return;
  }
  
  // 检查是否已存在相同发票号（当前批次）
  const hasDuplicateInBatch = recognitionResults.value.some(item => 
    item.is_invoice === true && item.data?.invoice_no === markForm.invoiceNo
  );
  
  // 将附件转换为发票并添加到识别结果中
  const newInvoice = {
    ...currentMarkItem.value,
    is_invoice: true,
    success: true,
    is_duplicate: hasDuplicateInBatch,
    data: {
      invoice_no: markForm.invoiceNo,
      date: markForm.date ? markForm.date : new Date(),
      type_description: hasDuplicateInBatch ? '手动标记发票（重复）' : '手动标记发票（有效）',
      items: []
    }
  };
  
  // 移除原附件
  recognitionResults.value = recognitionResults.value.filter(
    item => item._uid !== currentMarkItem.value._uid
  );
  
  // 添加新发票
  recognitionResults.value.push(newInvoice);
  
  // 如果是有效发票，自动添加到费用清单
  if (!hasDuplicateInBatch) {
    autoAddValidItems([newInvoice]);
  }
  
  manualMarkVisible.value = false;
  ElMessage.success(`已成功将附件标记为${hasDuplicateInBatch ? '重复' : '有效'}发票`);
};

const fieldMappings = {
  // 主表字段映射
  main: {
    'total_amount': 'total_sum'
  },
  // 项目明细字段映射
  items: {
    'name': 'item_name',
    'price': 'unit_price',
    'quantity': 'qty',
    'tax_amount': 'tax',
    'invoice_number': 'invoice_no',
    'invoice_date': 'inv_date',
    'merchant': 'merch_name',
    'merchant_tax_id': 'merch_tax_id',
    'buyer': 'buyer_name',
    'buyer_tax_id': 'buyer_tax_id',
    'invoice_type': 'inv_type',
    'source_file_name': 'source_file_nm',
    'file_hash': 'file_hash_val',
    'sort_order': 'sort'
  },
  // 附件字段映射
  attachments: {
    'filename': 'file_nm',
    'file_type': 'file_type_cd'
  }
};

// 提交报销函数 - 使用集中的字段映射配置
const submitReimbursement = async () => {
  // 增强数据验证
  if (!selectedCategory.value) {
    ElMessage.warning('请选择报销类型');
    return;
  }
  
  if (!reimbursementReason.value) {
    ElMessage.warning('请填写报销事由');
    return;
  }
  
  if (reimbursementList.value.length === 0) {
    ElMessage.warning('请添加报销项目');
    return;
  }
  
  try {
    isSubmitting.value = true;
    
    // 生成审批ID
    const approvalId = generateApprovalId();
    
    // 构建提交数据 - 使用字段映射配置确保一致性
    const submitData = {
      approval_id: approvalId,
      category: selectedCategory.value,
      reason: reimbursementReason.value,
      [fieldMappings.main.total_amount]: calculateTotal('Total'),
      total_tax: calculateTotal('Tax'),
      total_with_tax: calculateTotalAmountWithTax(),
      // 处理项目明细
      items: reimbursementList.value.map(item => ({
        [fieldMappings.items.name]: item.Name,
        [fieldMappings.items.price]: parseFloat(item.Price) || 0,
        [fieldMappings.items.quantity]: parseFloat(item.Quantity) || 0,
        subtotal: parseFloat(item.Total) || 0,
        [fieldMappings.items.tax_amount]: parseFloat(item.Tax) || 0,
        [fieldMappings.items.invoice_number]: item.source_invoice_no,
        [fieldMappings.items.invoice_date]: item.date,
        [fieldMappings.items.merchant]: item.merchant || '',
        [fieldMappings.items.merchant_tax_id]: item.merchantTaxId || '',
        [fieldMappings.items.buyer]: item.buyer || '',
        [fieldMappings.items.buyer_tax_id]: item.buyerTaxId || '',
        [fieldMappings.items.invoice_type]: item.invoiceType || '',
        source_file: item.source,
        [fieldMappings.items.source_file_name]: item.sourceFileName || '',
        [fieldMappings.items.file_hash]: item.fileHash || '',
        [fieldMappings.items.sort_order]: item.index
      })),
      attachments: submitAttachments().map(attach => ({
        [fieldMappings.attachments.filename]: attach.name,
        [fieldMappings.attachments.file_type]: attach.type === '发票' ? 'invoice' : 'attachment'
      }))
    };
    
    console.log('提交报销数据(使用字段映射配置):', submitData);
    // 输出字段映射关系用于调试
    console.log('字段映射关系:', fieldMappings);
    
    // 调用API提交报销
    const response = await axios.post('/api/reimbursement/submit', submitData, {
      timeout: 30000 // 30秒超时
    });
    
    if (response.data && response.data.success) {
      ElMessage.success('报销申请提交成功');
      pendingApprovalId.value = response.data.data.approval_id;
      
      // 提交成功后重置表单
      clearAll();
      
      console.log(`报销申请已提交，审批ID: ${pendingApprovalId.value}`);
    } else {
      ElMessage.error(`提交失败: ${response.data?.message || '未知错误'}`);
    }
  } catch (error) {
    // 详细错误日志
    console.error('提交报销失败:', {
      message: error.message,
      status: error.response?.status,
      statusText: error.response?.statusText,
      data: error.response?.data,
      url: error.config?.url
    });
    
    // 提取无效列名并显示
    if (error.response?.data?.msg) {
      const invalidColumns = error.response.data.msg.match(/列名 '([^']+)' 无效/g);
      if (invalidColumns) {
        console.error('无效的数据库列名:', invalidColumns);
        console.error('当前使用的字段映射:', fieldMappings);
        console.error('请根据以上信息调整字段映射配置');
      }
    }
    
    // 错误提示
    let errorMsg = '提交失败: ';
    if (error.response) {
      errorMsg += `服务器错误 (${error.response.status})`;
      if (error.response.status === 500) {
        errorMsg += `，服务器消息: ${error.response.data?.msg || '未知错误'}`;
        errorMsg += '，请联系后端获取正确的数据库字段名';
      } else if (error.response.status === 400) {
        errorMsg += `，数据格式错误: ${JSON.stringify(error.response.data)}`;
      }
    } else if (error.request) {
      errorMsg += '未收到服务器响应，请检查网络';
    } else {
      errorMsg += error.message;
    }
    ElMessage.error(errorMsg);
  } finally {
    isSubmitting.value = false;
  }
};


// 数字转中文大写
const convertToChinese = (num) => {
  if (isNaN(num)) return '';
  
  const n = parseFloat(num);
  if (n === 0) return '零元整';
  
  const digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
  const unit = ['', '拾', '佰', '仟', '万', '拾', '佰', '仟', '亿', '拾', '佰', '仟'];
  const decUnit = ['角', '分'];
  
  let integerPart = Math.floor(n).toString();
  let decimalPart = (n - Math.floor(n)).toFixed(2).slice(2);
  
  let res = '';
  
  // 处理整数部分
  for (let i = 0; i < integerPart.length; i++) {
    const digitIndex = parseInt(integerPart[i]);
    const unitIndex = integerPart.length - i - 1;
    res += digit[digitIndex] + unit[unitIndex];
  }
  
  res += '元';
 
  
  // 处理小数部分
  if (decimalPart === '00') {
    res += '整';
  } else {
    if (decimalPart[0] !== '0') {
      res += digit[parseInt(decimalPart[0])] + decUnit[0];
    }
    if (decimalPart[1] !== '0') {
      res += digit[parseInt(decimalPart[1])] + decUnit[1];
    }
  }
  
  // 替换特殊情况
  res = res.replace(/零+/g, '零').replace(/零([万亿])/g, '$1');
  res = res.replace(/零元/, '元').replace(/零角/, '').replace(/零分/, '');
  
  return res;
};
</script>

<style>
/* 添加角标样式 */
.valid-badge {
  color: #27ae60; /* 有效发票角标设置为绿色 */
  margin-left: 8px;
  background-color: transparent;
  border: 1px solid #27ae60;
}

.invalid-badge {
  color: #e74c3c; /* 无效发票、重复发票角标设置为红色 */
  margin-left: 8px;
  background-color: transparent;
  border: 1px solid #e74c3c;
}

.attachment-badge {
  color: #3498db; /* 普通附件角标设置为蓝色 */
  margin-left: 8px;
  background-color: transparent;
  border: 1px solid #3498db;
}

/* 空状态提示样式 */
.empty-hint {
  text-align: center;
  padding: 40px 0;
  color: #666;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.reimbursement-empty .empty-icon {
  font-size: 48px;
  color: #ccc;
  margin-bottom: 16px;
}

.reimbursement-empty .empty-text {
  font-size: 16px;
  margin-bottom: 8px;
  color: #333;
}

.reimbursement-empty .empty-description {
  color: #999;
  font-size: 14px;
  max-width: 400px;
  margin: 0 auto;
}

/* 发票内容区域样式 */
.invoice-content {
  margin-top: 16px;
  line-height: 1.6;
}

/* 卡片样式优化 */
.upload-card, .result-card, .reimbursement-card {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border-radius: 4px;
  overflow: hidden;
}

/* 识别状态弹窗样式 */
.recognition-status-container {
  padding: 10px 0;
}

.overall-progress {
  padding: 0 4px;
}

.file-progress-list {
  padding: 0 4px;
}

.file-progress-item:last-child {
  border-bottom: none;
}
</style>
